#include <stdio.h> 
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>

#include "sm2.h"
#include "common_func.h"
#include "core_time.h"

//BSP板级支持包所需全局变量
unsigned long UART_BASE = 0xbf000000;					//UART16550的虚地址
unsigned long CONFREG_TIMER_BASE = 0xbf20f100;			//CONFREG计数器的虚地址
unsigned long CONFREG_CLOCKS_PER_SEC = 50000000L;		//CONFREG时钟频率
unsigned long CORE_CLOCKS_PER_SEC = 33000000L;			//处理器核时钟频率


ECCrefPrivateKey prikey = {
	.K = {0x526FF0B7, 0x5DB2D940, 0x89FA76A1, 0x983DB034, 
		  0x0D79FF37, 0xACC58E21, 0x4FAE46A3, 0xC7DAE211}};

ECCrefPublicKey pubkey = {
	.x = {0x958E4164, 0x204F52F5, 0x4AE34032, 0x23EE5F42, 
		  0xE01ED9EB, 0xECBEE98B, 0x04424CCE, 0x1E7AABD4},
	.y = {0xB3891DE9, 0xBFB2F38F, 0x4F252C38, 0x0590F206, 
		  0xBDA63306, 0x626B646C, 0x76C1D7D9, 0x15D464F5}};

uint32_t random_k[8] = {
	0x16a25a3d, 0x8e495e9e, 0xfeeb31ce, 0x49e0f38e,   
	0x0d00828e, 0xf8b0c6b4, 0x2b811458, 0x03f0b21f};

uint32_t hash_result[8] = {
	0xc7e8337e, 0xff9f56b1, 0x5ebab182, 0x0051d05f, 
	0x687ed7f4, 0xaaef99cc, 0x3bb277ee, 0xc2101fa2};
		  
ECCSignature signature_result = {0};

uint8_t sign_done = 0;
uint8_t sm2_mode = 0;

int main(int argc, char** argv)
{
	printf("\nHello Loongarch32r SM2 INT!\n");

	uint32_t ret = 0;
	
	sm2_mode = 0;
	sm2_signature_int(&prikey, random_k, hash_result);
	while(1){
		delay_ms(1);	//如果不添加仿真会失败
		if(sign_done == 1)
		{
			break;
		}
	}
	
	sm2_mode = 1;
	sm2_verify_int(&pubkey, &signature_result, hash_result);
	
	while(1)
	{

	}
	
	return 0;
}

uint32_t sm2_call_back()
{
	if(sm2_mode == 0)
	{
		sm2_signature_callback(&signature_result);
		printf("SM2 signature done!\n");
		sign_done = 1;
	}
	else
	{
		int ret = sm2_verify_callback();
		if (ret == 0) {
			printf("SM2 verify success.\n");
		} else {
			printf("SM2 verify Faild with 0x%x.\n", ret);
		}
		printf("SM2 INT test finished!\n");
	}
	RegWrite(0xbf20f00c, 0x80);//clr
}


void HWI0_IntrHandler(void)
{	
	unsigned int int_state;
	int_state = RegRead(0xbf20f014);

	if((int_state) == 0x80){
		sm2_call_back();
	}
}
